<?php
/*
 * Created on 07.01.2007
 *
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 */

m2import("phpinchains/psp/OutputListener.php");

/**
 * Output writer for PSPs. 
 * 
 * Used instead of print in a psp.
 */
class phpinchains_psp_OutputWriter
{
    
    protected $listenerstack = array();
    protected $listeners = array();
    protected $topstack = 0;


    function phpinchains_psp_OutputWriter ()
    {
        $this->listenerstack[] = new phpinchains_psp_OutputListener();
    }
    
    function pushListener(& $listener)
    {
        $this->topstack++;
        $this->listenerstack[$this->topstack] = & $listener;
    }

    function popListener()
    {
        if ($this->topstack == 0)
            die("Listener stack height lower than zero! popListener is called to often!");
        unset($this->listenerstack[$this->topstack]);
        $this->topstack--;
    }

    function write ($str)
    {
                
        $this->listenerstack[$this->topstack]->write($str);
        if (count($this->listeners))
        {
            foreach ($this->listeners as $n => $v)
                $listener->write($str);
        }
    }

    /**
     * Get the root listener.
     *
     * Writing to root listener will allways be displayed, regardless of body processing of a tag.
     *
     * @return <type>
     */
    function getRootListener() {
        return $this->listenerstack[0];
    }
    
    /**
     * Registers a listener, which captures all input until it is unregistered
     * 
     * @param string name Identifier for the listener
     * @param phpinchains_psp_OutputListener listener The listener to register 
     */
    function registerListener ($name, & $listener)
    {
        $this->listeners[$name] = & $listener;
    }
    
    /**
     * Unregisters a listener
     * 
     * @param string name Identifier which was used to register the listener
     */
    function unregisterListener ($name)
    {
        unset($this->listeners[$name]);
    }

    /**
     * Get listener by name
     * 
     * @param string name Identifier which was used to register the listener
     */
    function getListener ($name)
    {
        if (isset($this->listeners[$name]))
            return $this->listeners[$name];
    }
       
    function getBuffer ()
    {
        return $this->listenerstack[$this->topstack]->getBuffer();
    }
    
    function clearBuffer () {
        $this->listenerstack[$this->topstack]->clearBuffer();
    }
    
    function clearBufferStack ()
    {
        for ($i = 0; $i < count($this->listenerstack); $i++) {
            $this->listenerstack[$i]->clearBuffer();
        }
    } 
    
}
?>
